<?php

namespace app\common\oauth2;

/**
 * 创建OAuth2 Server对象
 */
trait Server
{
    protected $_oauth2Server  = null;
    protected $_oauth2Storage = null;

    protected function initOAuth2()
    {
        if(!$this->_oauth2Server) {
            $this->oauthServer();
        }
    }

    protected function oauthServer()
    {

        $type     = config('database.type');
        $database = config('database.database');
        $hostname = config('database.hostname');
        $dsn      = "{$type}:dbname={$database};host={$hostname}";
        $username = config('database.username');
        $password = config('database.password');
        // error reporting (this is a demo, after all!)

        ini_set('display_errors', 1);
        error_reporting(E_ALL);
        \OAuth2\Autoloader::register();

        $this->_oauth2Storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' =>
            $password));

        // Pass a storage object or array of storage objects to the OAuth2 server class
        $this->_oauth2Server = new \OAuth2\Server($this->_oauth2Storage);

        // Add the "Client Credentials" grant type (it is the simplest of the grant types)
        $this->_oauth2Server->addGrantType(new \OAuth2\GrantType\ClientCredentials($this->_oauth2Storage));

        // Add the "Authorization Code" grant type (this is where the oauth magic happens)
        $this->_oauth2Server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($this->_oauth2Storage));
    }

    /**
     *验证access_token
     */
    protected function checkOauth()
    {

        if (!$this->_oauth2Server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
//            $this->_oauth2Server->send();
            header("Content-Type:application/json");
            $response = [
                'status'=>0,
                'msg'=>'invalid_token',
                'data'=>[],
            ];
            exit(json_encode($response));
        }

    }

    protected function fetchTokenResponseBody()
    {

        // Handle a request for an OAuth2.0 Access Token and send the response to the client
        return $this->_oauth2Server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->getResponseBody();
    }

}